Skip to content

Conversation

@sahar-fehri
Copy link
Contributor

@sahar-fehri sahar-fehri commented Dec 9, 2025

Description

Optimizes TokenListController storage to reduce write amplification by persisting tokensChainsCache via StorageService using per-chain files instead of a single monolithic state property.

Related: https://github.com/MetaMask/metamask-mobile/pull/22943/files

Related: https://github.com/MetaMask/decisions/pull/110

Related: #7192

Explanation

The tokensChainsCache (~5MB total, containing token lists for all chains) was persisted as part of the controller state. Every time a single chain's token list was updated (~100-500KB), the entire ~5MB cache was rewritten to disk, causing:

  • Startup performance issues (loading large state on app initialization)
  • Runtime performance degradation (frequent large writes during token fetches)
  • Impacts both extension

Solution

Per-Chain File Storage:
Each chain's cache is now stored in a separate file (e.g., tokensChainsCache:0x1, tokensChainsCache:0x89)
Only the updated chain (~100-500KB) is written on each token fetch, reducing write operations by ~90-95%
All chains are loaded in parallel at startup to maintain compatibility with TokenDetectionController
Key Changes:

  • Set tokensChainsCache metadata to persist: false to prevent framework-managed persistence
  • Added #loadCacheFromStorage() to load all per-chain files in parallel on initialization
  • Added #saveChainCacheToStorage(chainId) to persist only the specific chain that changed
  • Added #migrateStateToStorage() to automatically migrate existing cache data on first launch after upgrade
  • Updated clearingTokenListData() to remove all per-chain files

References

Checklist

  • I've updated the test suite for new or updated code as appropriate
  • I've updated documentation (JSDoc, Markdown, etc.) for new or updated code as appropriate
  • I've communicated my changes to consumers by updating changelogs for packages I've changed
  • I've introduced breaking changes in this PR and have prepared draft pull requests for clients and consumer packages to resolve them

Note

BREAKING: TokenListController persists tokensChainsCache via StorageService using per-chain files; state metadata for tokensChainsCache set to persist: false.

  • Adds #initializeFromStorage, #loadCacheFromStorage (parallel per-chain load), #saveChainCacheToStorage, and #migrateStateToStorage
  • Updates fetchTokenList to await init, write only the updated chain, and avoid refreshing timestamps on failed fetches
  • Makes clearingTokenListData async to remove all per-chain files (with partial-failure handling) and clears state accordingly
  • Refactors internals (private # fields, polling stop method) and improves network-change handling
  • Adds @metamask/storage-service dependency and tsconfig references; updates changelog
  • Expands tests to mock StorageService, cover migration/load/save/clear flows, and adjust for async behaviors

Written by Cursor Bugbot for commit 71124a6. This will update automatically on new commits. Configure here.

tokensChainsCache: {
includeInStateLogs: false,
persist: true,
persist: false, // Persisted separately via StorageService
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Making this false to block disk writes

salimtb
salimtb previously approved these changes Dec 16, 2025
andrepimenta
andrepimenta previously approved these changes Dec 18, 2025

// Load cache from StorageService on initialization and handle migration.
// Store the promise so other methods can await it to avoid race conditions.
this.#initializationPromise = this.#initializeFromStorage();
Copy link
Member

@Gudahtt Gudahtt Jan 9, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generally it's discouraged to make async calls in the constructor. This can complicate unit tests (both here and in modules that import this), and it gives less control to the caller over how initialization happens.

For example, we're been looking more lately at speeding up initialization, potentially delaying slower initialization steps until more critical steps have finished already (especially on mobile). If this happens in the constructor, there is no way to delay it without delaying construction of the controller itself (which would be quite complex).

Instead what we recommend is to move this to an init function, and update both clients to call that init function after construction. A number of other controllers already, e.g. AccountTreeController. This is easier to test, easier to mock on the platform side, and makes it easy for the platform team to optimize initialization.

*
* @returns A promise that resolves when migration is complete.
*/
async #migrateStateToStorage(): Promise<void> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could do this in a client migration instead. That's where we usually migrate state.

* - Successfully removed chains are cleared from state
* - Failed removals are kept in state to maintain consistency with storage
*
* Acquires the mutex to prevent race conditions with fetchTokenList.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need a mutex here? I don't understand what race condition we're protecting against here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would recommend that we keep the persisted state synchronized at all times, rather than updating it in each location where state is updated. That ensures we won't forget to update it somewhere, and avoids duplication, and makes it easier to reason about overlapping operations/race conditions.

e.g. we could do something like this:

this.messenger.subscribe(
 'TokenListController:stateChange',
 (tokensChainsCache: TokenListControllerState['tokensChainsCache']) => persistCache(tokensChainsCache),
 (state: TokenListControllerState) => state.tokensChainsCache,

Then within persistCache, we can do things like:

  • protect against concurrent operations
  • debounce state updates so they aren't saved too frequently

All without using a mutex. Better to avoid the need for a mutex if possible, since waiting for a mutex can take an unpredictable amount of time, and it's easy to accidentally create deadlocks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants